<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Redis 缓存更新策略 | 戴涛的宝藏</title><meta name="author" content="戴涛"><meta name="copyright" content="戴涛"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Redis 缓存更新策略使用 Redis 作为缓存，可以提高客户端的响应，借助内存的读取速度快速返回。一旦程序中使用到了Redis 缓存，不可以避免的需要维护 Redis 和 MySQL 数据的一致性。 Redis 常见的缓存更新策略 内存淘汰 键值过期删除策略（懒惰删除 + 定期删除） 程序主动更新      内存淘汰 超时剔除 主动更新    说明 不用自己维护，利用Redis内存淘汰策略 给">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis 缓存更新策略">
<meta property="og:url" content="https://declan1.gitee.io/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5/index.html">
<meta property="og:site_name" content="戴涛的宝藏">
<meta property="og:description" content="Redis 缓存更新策略使用 Redis 作为缓存，可以提高客户端的响应，借助内存的读取速度快速返回。一旦程序中使用到了Redis 缓存，不可以避免的需要维护 Redis 和 MySQL 数据的一致性。 Redis 常见的缓存更新策略 内存淘汰 键值过期删除策略（懒惰删除 + 定期删除） 程序主动更新      内存淘汰 超时剔除 主动更新    说明 不用自己维护，利用Redis内存淘汰策略 给">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://img.lovetao.top/img/202303152100335.jpg">
<meta property="article:published_time" content="2023-03-17T15:53:00.000Z">
<meta property="article:modified_time" content="2023-03-22T06:36:17.187Z">
<meta property="article:author" content="戴涛">
<meta property="article:tag" content="Redis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img.lovetao.top/img/202303152100335.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://declan1.gitee.io/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Redis 缓存更新策略',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-22 14:36:17'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://img.lovetao.top/img/202303152100335.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">61</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">9</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">9</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-tags"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img.lovetao.top/img/202303152113310.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="戴涛的宝藏"><span class="site-name">戴涛的宝藏</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-tags"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Redis 缓存更新策略</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-03-17T15:53:00.000Z" title="Created 2023-03-17 23:53:00">2023-03-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-03-22T06:36:17.187Z" title="Updated 2023-03-22 14:36:17">2023-03-22</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Redis/">Redis</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Redis 缓存更新策略"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Redis-缓存更新策略"><a href="#Redis-缓存更新策略" class="headerlink" title="Redis 缓存更新策略"></a>Redis 缓存更新策略</h1><p>使用 Redis 作为缓存，可以提高客户端的响应，借助内存的读取速度快速返回。一旦程序中使用到了Redis 缓存，不可以避免的需要维护 Redis 和 MySQL 数据的一致性。</p>
<h2 id="Redis-常见的缓存更新策略"><a href="#Redis-常见的缓存更新策略" class="headerlink" title="Redis 常见的缓存更新策略"></a>Redis 常见的缓存更新策略</h2><ul>
<li>内存淘汰</li>
<li>键值过期删除策略（懒惰删除 + 定期删除）</li>
<li>程序主动更新</li>
</ul>
<table>
<thead>
<tr>
<th></th>
<th>内存淘汰</th>
<th>超时剔除</th>
<th>主动更新</th>
</tr>
</thead>
<tbody><tr>
<td>说明</td>
<td>不用自己维护，利用Redis内存淘汰策略</td>
<td>给缓存数据添加 TTL 时间，到期后自动删除缓存，下次查询时更新缓存</td>
<td>编写业务逻辑，再修改数据库的同时，更新缓存</td>
</tr>
<tr>
<td>一致性</td>
<td>差</td>
<td>一般</td>
<td>好</td>
</tr>
<tr>
<td>维护成本</td>
<td>无</td>
<td>低</td>
<td>搞</td>
</tr>
</tbody></table>
<p>业务场景：</p>
<ul>
<li>低一致性需求：使用内存淘汰机制。例如店铺类型的查询缓存</li>
<li>高一致性需求：主动更新，并以超时剔除作为兜底方案。例如店铺详情查询的缓存</li>
</ul>
<h3 id="主动更新策略"><a href="#主动更新策略" class="headerlink" title="主动更新策略"></a>主动更新策略</h3><h4 id="方案一：旁路缓存模式"><a href="#方案一：旁路缓存模式" class="headerlink" title="方案一：旁路缓存模式"></a>方案一：旁路缓存模式</h4><p>由缓存的调用者，在更新数据库的同时更新缓存。</p>
<h4 id="方案二：Read-x2F-Write-Through-Pattern"><a href="#方案二：Read-x2F-Write-Through-Pattern" class="headerlink" title="方案二：Read&#x2F;Write Through Pattern"></a>方案二：Read&#x2F;Write Through Pattern</h4><p>缓存与数据库整合为一个服务，由服务来维护一致性。调用者调用该服务，无需关心缓存一致性问题。</p>
<h4 id="方案三：Write-Behind-Caching-Pattern"><a href="#方案三：Write-Behind-Caching-Pattern" class="headerlink" title="方案三：Write Behind Caching Pattern"></a>方案三：Write Behind Caching Pattern</h4><p>调用者只需操作缓存，由其他线程异步的将缓存数据持久化到数据库中，保证最终一致性。</p>
<p>方案三是一致性和可靠性难以保持的：</p>
<ul>
<li>一个线程实时去监控，一致性很难保存。</li>
<li>缓存操作了上百次，还没有触发异步操作去写入数据库。缓存失效了，数据丢失。可靠性很难保证</li>
</ul>
<h3 id="旁路缓存更新"><a href="#旁路缓存更新" class="headerlink" title="旁路缓存更新"></a>旁路缓存更新</h3><h4 id="更新缓存还是删除缓存"><a href="#更新缓存还是删除缓存" class="headerlink" title="更新缓存还是删除缓存"></a>更新缓存还是删除缓存</h4><p>更新缓存：每次更新数据库都更新缓存，无效写操作较多；而且可能会产生数据并发问题，例如一个线程插入到另一个线程中间执行。</p>
<p>删除缓存：更新数据库时让缓存失效，查询时在更新缓存</p>
<p>最终答案：删除缓存</p>
<h4 id="先更新数据库，还是先删除缓存？"><a href="#先更新数据库，还是先删除缓存？" class="headerlink" title="先更新数据库，还是先删除缓存？"></a>先更新数据库，还是先删除缓存？</h4><h5 id="先删除缓存，再更新数据库"><a href="#先删除缓存，再更新数据库" class="headerlink" title="先删除缓存，再更新数据库"></a><strong>先删除缓存，再更新数据库</strong></h5><p>在「读 + 写」并发的时候，还是会出现缓存和数据库的数据不一致的问题。</p>
<p>问题：</p>
<p><img src="https://cdn.xiaolincoding.com//mysql/other/cc208c2931b4e889d1a58cb655537767.png" alt="图片"></p>
<h5 id="先更新数据库，在删除缓存"><a href="#先更新数据库，在删除缓存" class="headerlink" title="先更新数据库，在删除缓存"></a>先更新数据库，在删除缓存</h5><p>继续用「读 + 写」请求的并发的场景来分析。读取为空 + 写入操作</p>
<p><img src="https://cdn.xiaolincoding.com//mysql/other/1cc7401143e79383ead96582ac11b615.png" alt="图片"></p>
<p>最终，该用户年龄在缓存中是 20（旧值），在数据库中是 21（新值），缓存和数据库数据不一致。</p>
<p>从上面的理论上分析，先更新数据库，再删除缓存也是会出现数据不一致性的问题，<strong>但是在实际中，这个问题出现的概率并不高</strong>。</p>
<p><strong>因为缓存的写入通常要远远快于数据库的写入</strong>，所以在实际中很难出现请求 B 已经更新了数据库并且删除了缓存，请求 A 才更新完缓存的情况。</p>
<p>而一旦请求 A 早于请求 B 删除缓存之前更新了缓存，那么接下来的请求就会因为缓存不命中而从数据库中重新读取数据，所以不会出现这种不一致的情况。</p>
<blockquote>
<p>正因为写缓存的速度要远远小于写入硬盘的速度，所以读取线程一般情况下都会快于写入线程</p>
</blockquote>
<p>所以，<strong>「先更新数据库 + 再删除缓存」的方案，是可以保证数据一致性的</strong>。</p>
<p>而且阿旺为了确保万无一失，还给缓存数据加上了「<strong>过期时间</strong>」，就算在这期间存在缓存数据不一致，有过期时间来兜底，这样也能达到最终一致。</p>
<h6 id="思考"><a href="#思考" class="headerlink" title="思考"></a>思考</h6><p>以为没问题了吗，其实再仔细想想还是会出现问题，如果先更新玩数据库，另外一个线程没有删除缓存，那么用户在缓存失效前访问的都是旧数据，出现了数据一致性。至于为什么两个操作没有同时完成，可能是因为网络波动也有可能是因为 Redis 宕机了。</p>
<h1 id="思考-1"><a href="#思考-1" class="headerlink" title="思考"></a>思考</h1><h2 id="更新数据库-更新缓存方案改进"><a href="#更新数据库-更新缓存方案改进" class="headerlink" title="更新数据库 + 更新缓存方案改进"></a><strong>更新数据库 + 更新缓存</strong>方案改进</h2><p>[ 先更新数据库，再删除缓存」的方案虽然保证了数据库与缓存的数据一致性，但是每次更新数据的时候，缓存的数据都会被删除，这样会对缓存的命中率带来影响。</p>
<p>所以，<strong>如果我们的业务对缓存命中率有很高的要求，我们可以采用「更新数据库 + 更新缓存」的方案，因为更新缓存并不会出现缓存未命中的情况</strong>。</p>
<p>但是这个方案前面我们也分析过，在两个更新请求并发执行的时候，会出现数据不一致的问题，因为更新数据库和更新缓存这两个操作是独立的，而我们又没有对操作做任何并发控制，那么当两个线程并发更新它们的话，就会因为写入顺序的不同造成数据的不一致。</p>
<p><strong>并发问题：</strong></p>
<p>举个例子，比如「请求 A 」和「请求 B 」两个请求，同时更新「同一条」数据，则可能出现这样的顺序：</p>
<p>A 请求先将数据库的数据更新为 1，然后在更新缓存前，请求 B 将数据库的数据更新为 2，紧接着也把缓存更新为 2，然后 A 请求更新缓存为 1。此时，数据库中的数据是 2，而缓存中的数据却是 1，<strong>出现了缓存和数据库中的数据不一致的现象</strong>。</p>
<p><img src="https://cdn.xiaolincoding.com//mysql/other/8febac10b14bed16cb96d1d944cd08da.png" alt="图片"></p>
<p>所以我们得增加一些手段来解决这个问题，这里提供两种做法：</p>
<ul>
<li>在更新缓存前先加个<strong>分布式锁</strong>，保证同一时间只运行一个请求更新缓存，就会不会产生并发问题了，当然引入了锁后，对于写入的性能就会带来影响。</li>
<li>在更新完缓存时，给缓存加上较短的<strong>过期时间</strong>，这样即时出现缓存不一致的情况，缓存的数据也会很快过期，对业务还是能接受的。</li>
</ul>
<h2 id="先删除缓存，再更新数据库方案改进"><a href="#先删除缓存，再更新数据库方案改进" class="headerlink" title="先删除缓存，再更新数据库方案改进"></a>先删除缓存，再更新数据库方案改进</h2><p>先删除缓存，再更新数据库」方案在「读 + 写」并发请求而造成缓存不一致的解决办法是「<strong>延迟双删</strong>」。</p>
<p>延迟双删实现的伪代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#删除缓存</span><br><span class="line">redis.delKey(X)</span><br><span class="line">#更新数据库</span><br><span class="line">db.update(X)</span><br><span class="line">#睡眠</span><br><span class="line">Thread.sleep(N)</span><br><span class="line">#再删除缓存</span><br><span class="line">redis.delKey(X)</span><br></pre></td></tr></table></figure>



<h2 id="先更新数据库，再删缓存改进"><a href="#先更新数据库，再删缓存改进" class="headerlink" title="先更新数据库，再删缓存改进"></a>先更新数据库，再删缓存改进</h2><p>之前在思考中跟大家说过这个问题：如果两个操作没有同时完成，会在一定时期内出现缓存不一致问题。</p>
<p>所以我们的改进策略目的主要是保证更新数据库和删除缓存两个动作同时执行。</p>
<p>两种方法：</p>
<ul>
<li>重试机制。</li>
<li>订阅 MySQL binlog，再操作缓存。</li>
</ul>
<p>注意：这两个方法都是基于异步的操作。</p>
<h3 id="重试机制"><a href="#重试机制" class="headerlink" title="重试机制"></a>重试机制</h3><p>我们可以引入<strong>消息队列</strong>，将第二个操作（删除缓存）要操作的数据加入到消息队列，由消费者来操作数据。</p>
<ul>
<li>如果应用<strong>删除缓存失败</strong>，可以从消息队列中重新读取数据，然后再次删除缓存，这个就是<strong>重试机制</strong>。当然，如果重试超过的一定次数，还是没有成功，我们就需要向业务层发送报错信息了。</li>
<li>如果<strong>删除缓存成功</strong>，就要把数据从消息队列中移除，避免重复操作，否则就继续重试。</li>
</ul>
<p>重试机制的过程：</p>
<p><img src="https://cdn.xiaolincoding.com//mysql/other/a4440f0d572612e0832b903e4a62bd2b.png" alt="图片"></p>
<h3 id="订阅-MySQL-binlog，再操作缓存"><a href="#订阅-MySQL-binlog，再操作缓存" class="headerlink" title="订阅 MySQL binlog，再操作缓存"></a>订阅 MySQL binlog，再操作缓存</h3><p><strong>第一步是更新数据库</strong>，那么更新数据库成功，就会产生一条变更日志，记录在 binlog 里。</p>
<p>于是我们就可以通过订阅 binlog 日志，拿到具体要操作的数据，然后再执行缓存删除，阿里巴巴开源的 Canal 中间件就是基于这个实现的。</p>
<p>Canal 模拟 MySQL 主从复制的交互协议，把自己伪装成一个 MySQL 的从节点，向 MySQL 主节点发送 dump 请求，MySQL 收到请求后，就会开始推送 Binlog 给 Canal，Canal 解析 Binlog 字节流之后，转换为便于读取的结构化数据，供下游程序订阅使用。</p>
<p>Canal 工作原理：</p>
<p><img src="https://cdn.xiaolincoding.com//mysql/other/2ee2280e9f59b6b4879ebdec6eb0cf52.png" alt="图片"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://declan1.gitee.io">戴涛</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://declan1.gitee.io/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5/">https://declan1.gitee.io/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Redis/">Redis</a></div><div class="post_share"><div class="social-share" data-image="https://img.lovetao.top/img/202303152100335.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/17/%E7%99%BE%E4%B8%87%E7%BA%A7-Excel-%E6%95%B0%E6%8D%AE%E5%AF%BC%E5%87%BA/" title="百万级 Excel 数据导出"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">百万级 Excel 数据导出</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9%E3%80%81%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%E3%80%81%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF/" title="Redis 缓存雪崩、缓存穿透、缓存击穿"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">Redis 缓存雪崩、缓存穿透、缓存击穿</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/03/17/Redis-%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9%E3%80%81%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%E3%80%81%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF/" title="Redis 缓存雪崩、缓存穿透、缓存击穿"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-17</div><div class="title">Redis 缓存雪崩、缓存穿透、缓存击穿</div></div></a></div><div><a href="/2023/03/17/Redis-%E4%B8%BB%E4%BB%8E%E6%9E%B6%E6%9E%84/" title="Redis 主从架构"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-17</div><div class="title">Redis 主从架构</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://img.lovetao.top/img/202303152100335.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">戴涛</div><div class="author-info__description">虽平凡，但不甘于平凡</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">61</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">9</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/declan1" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:coder_tao@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Redis-%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5"><span class="toc-number">1.</span> <span class="toc-text">Redis 缓存更新策略</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Redis-%E5%B8%B8%E8%A7%81%E7%9A%84%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5"><span class="toc-number">1.1.</span> <span class="toc-text">Redis 常见的缓存更新策略</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E5%8A%A8%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5"><span class="toc-number">1.1.1.</span> <span class="toc-text">主动更新策略</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E6%97%81%E8%B7%AF%E7%BC%93%E5%AD%98%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.1.1.1.</span> <span class="toc-text">方案一：旁路缓存模式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9ARead-x2F-Write-Through-Pattern"><span class="toc-number">1.1.1.2.</span> <span class="toc-text">方案二：Read&#x2F;Write Through Pattern</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%B8%89%EF%BC%9AWrite-Behind-Caching-Pattern"><span class="toc-number">1.1.1.3.</span> <span class="toc-text">方案三：Write Behind Caching Pattern</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%97%81%E8%B7%AF%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0"><span class="toc-number">1.1.2.</span> <span class="toc-text">旁路缓存更新</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9B%B4%E6%96%B0%E7%BC%93%E5%AD%98%E8%BF%98%E6%98%AF%E5%88%A0%E9%99%A4%E7%BC%93%E5%AD%98"><span class="toc-number">1.1.2.1.</span> <span class="toc-text">更新缓存还是删除缓存</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%88%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%8C%E8%BF%98%E6%98%AF%E5%85%88%E5%88%A0%E9%99%A4%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">1.1.2.2.</span> <span class="toc-text">先更新数据库，还是先删除缓存？</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%85%88%E5%88%A0%E9%99%A4%E7%BC%93%E5%AD%98%EF%BC%8C%E5%86%8D%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">1.1.2.2.1.</span> <span class="toc-text">先删除缓存，再更新数据库</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%85%88%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%8C%E5%9C%A8%E5%88%A0%E9%99%A4%E7%BC%93%E5%AD%98"><span class="toc-number">1.1.2.2.2.</span> <span class="toc-text">先更新数据库，在删除缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%80%9D%E8%80%83"><span class="toc-number">1.1.2.2.2.1.</span> <span class="toc-text">思考</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%80%9D%E8%80%83-1"><span class="toc-number">2.</span> <span class="toc-text">思考</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%9B%B4%E6%96%B0%E7%BC%93%E5%AD%98%E6%96%B9%E6%A1%88%E6%94%B9%E8%BF%9B"><span class="toc-number">2.1.</span> <span class="toc-text">更新数据库 + 更新缓存方案改进</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%88%E5%88%A0%E9%99%A4%E7%BC%93%E5%AD%98%EF%BC%8C%E5%86%8D%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93%E6%96%B9%E6%A1%88%E6%94%B9%E8%BF%9B"><span class="toc-number">2.2.</span> <span class="toc-text">先删除缓存，再更新数据库方案改进</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%88%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%8C%E5%86%8D%E5%88%A0%E7%BC%93%E5%AD%98%E6%94%B9%E8%BF%9B"><span class="toc-number">2.3.</span> <span class="toc-text">先更新数据库，再删缓存改进</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E8%AF%95%E6%9C%BA%E5%88%B6"><span class="toc-number">2.3.1.</span> <span class="toc-text">重试机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%A2%E9%98%85-MySQL-binlog%EF%BC%8C%E5%86%8D%E6%93%8D%E4%BD%9C%E7%BC%93%E5%AD%98"><span class="toc-number">2.3.2.</span> <span class="toc-text">订阅 MySQL binlog，再操作缓存</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/28/HTTP-1-1%E3%80%81HTTP-2%E3%80%81HTTP-3-%E6%BC%94%E5%8F%98/" title="HTTP/1.1、HTTP/2、HTTP/3 演变">HTTP/1.1、HTTP/2、HTTP/3 演变</a><time datetime="2023-03-28T15:30:00.000Z" title="Created 2023-03-28 23:30:00">2023-03-28</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E7%9A%84%E5%BA%94%E7%94%A8%E6%95%B0%E6%8D%AE%E6%98%AF%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E5%AE%8C%E6%95%B4%E6%80%A7%E7%9A%84%EF%BC%9F/" title="HTTPS 的应用数据是如何保证完整性的？">HTTPS 的应用数据是如何保证完整性的？</a><time datetime="2023-03-24T09:25:00.000Z" title="Created 2023-03-24 17:25:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E6%98%AF%E5%A6%82%E4%BD%95%E5%BB%BA%E7%AB%8B%E8%BF%9E%E6%8E%A5%E7%9A%84%EF%BC%9F/" title="HTTPS 是如何建立连接的？">HTTPS 是如何建立连接的？</a><time datetime="2023-03-24T09:25:00.000Z" title="Created 2023-03-24 17:25:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/HTTPS-%E4%B8%80%E5%AE%9A%E5%AE%89%E5%85%A8%E5%8F%AF%E9%9D%A0%E5%90%97%EF%BC%9F/" title="HTTPS 一定安全可靠吗？">HTTPS 一定安全可靠吗？</a><time datetime="2023-03-24T09:24:00.000Z" title="Created 2023-03-24 17:24:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/%E5%AE%9E%E6%88%98/" title="实战">实战</a><time datetime="2023-03-23T13:52:00.000Z" title="Created 2023-03-23 21:52:00">2023-03-23</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://img.lovetao.top/img/202303152113310.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 戴涛</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'cEUNK0k7aOSrnE93yOEHT9io-gzGzoHsz',
      appKey: '3oME0qpmzHlf1QmZiMY9i8rs',
      avatar: 'declan',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>